<template>
  <div>
    <HeaderPage />
    <SearchHeader></SearchHeader>
    <navPage></navPage>
    <div class="box">
      <img src="../../assets/img/carBg.png" alt="" />
      <div class="address-box">
        <div class="address-title clearfix">
          <p class="fl">收货人信息</p>
          <p class="add-address-btn fr" @click="addAndEditAddress('add')">
            新增地址
          </p>
        </div>
        <div class="address-info">
          <div
            class="address-list clearfix"
            v-for="(item, index) in addressList"
            :key="index"
          >
            <p class="name fl">{{ item.name }}</p>
            <p class="address fl">{{ item.address }}</p>
            <p class="phone fl">手机：{{ item.phone }}</p>
            <div class="set-default fl">
              <img
                src="../../assets/img/defaultIcon.png"
                alt=""
                v-if="item.isDefault"
              />
              <img
                src="../../assets/img/noSelect.png"
                alt=""
                v-else
                @click="setDefault(index)"
              />
              <span v-if="item.isDefault">默认地址</span>
              <span v-else>设为默认地址</span>
            </div>
            <div class="edit fr clearfix">
              <p @click="editAddr(item)">编辑</p>
              <p @click="delAddr(item, index)">删除</p>
            </div>
          </div>
        </div>
      </div>
      <div class="goods-box">
        <div class="goods-table-head clearfix">
          <p>商品</p>
          <p>单价</p>
          <p>数量</p>
          <p>小计</p>
          <p>操作</p>
        </div>
        <div class="goods-box-list">
          <div
            class="goods-list clearfix"
            v-for="(item, index) in goodsList"
            :key="index"
          >
            <div class="goods-info fl clearfix">
              <img
                src="../../assets/img/product1.png"
                alt=""
                class="goods-pic fl"
              />
              <div class="goods-info-detail">
                <p class="goods-name">
                  {{ item.materialName }}
                </p>
                <p class="other-info">
                  <span>规格：{{ item.standName }}</span>
                  <span>所属商家：{{ item.merchant }}</span>
                </p>
              </div>
            </div>
            <p class="price fl">¥ {{ item.price }}</p>
            <div class="buy-num fl">
              <el-input-number
                v-model="item.num"
                @change="handleChange"
                :min="1"
                :max="100"
                label="描述文字"
              ></el-input-number>
            </div>
            <div class="small-total fl">
              <span>￥</span
              ><span>{{ (item.price * item.num).toFixed(2) }}</span>
            </div>
            <p class="del-goods fr" @click="delGoods(index)">删除</p>
          </div>
          <div class="total-box clearfix">
            <div class="atonce-btn fr" @click="submitClick">下单</div>
            <div class="total fr">
              <span>总价：</span>
              <span>￥{{ totalMoney }}</span>
            </div>
            <span>
              <span class="wuliuClass">物流方式：线下自提</span>
            </span>
          </div>
        </div>
      </div>
    </div>
    <FooterPage></FooterPage>
  </div>
</template>
<script>
import HeaderPage from "../../components/head";
import SearchHeader from "../indexHome/searchHeader";
import FooterPage from "../../components/footer";
import navPage from "../../components/nav";
export default {
  components: {
    HeaderPage,
    SearchHeader,
    FooterPage,
    navPage,
  },
  watch: {
    goodsList(val, old) {
      console.log(old);
      console.log(val);
      this.totalMoneyCompunted();
    },
  },
  data() {
    return {
      addressList: [],
      goodsList: [],
      num: "",
      totalMoney: 0,
    };
  },
  mounted() {},
  mounted() {
    //获取传递的数据
    var item = JSON.parse(this.$route.query.item);
    console.log(item);
    this.getSlGodds(item);
    this.getAddrList(); //获取地址列表
    this.totalMoneyCompunted();
  },
  methods: {
    setDefault(index) {
      var list = this.addressList;
      for (var k in list) {
        if (k == index) {
          list[k].isDefault = true;
          this.setUpdateDefaultAddr(list[k], "1");
        } else {
          list[k].isDefault = false;
        }
      }
      this.addressList = list;
    },
    handleChange() {
      this.totalMoneyCompunted();
    },
    //删除购物车商品
    delGoods(index) {
      var list = JSON.parse(JSON.stringify(this.goodsList));

      var delGoods = list[index];

      this.$confirm("您确认要删除该商品吗。", "删除商品？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //确认：执行删除操作
          this.$http("delete", "/sys/iaShoppingTrolley/delete.do", {
            id: delGoods.id, //购物车记录id
          }).then((res) => {
            if (res.code == "0000") {
              list.splice(index, 1);
              this.goodsList = list;
              this.$http("get", "/sys/iaShoppingTrolley/findPage.do", {
                pageNum: 1,
                pageSize: 10,
              }).then((res) => {
                if (res.code == "0000") {
                  this.$store.commit("joinCar", res.result.total);
                }
              });
            }
          });
        })
        .catch(() => {
          //取消：不执行任何操作
        });
    },
    totalMoneyCompunted() {
      var list = JSON.parse(JSON.stringify(this.goodsList));
      var total = 0;
      for (var k in list) {
        total += list[k].num * Number(list[k].price);
      }
      this.totalMoney = total.toFixed(2);
    },
    addAndEditAddress(type) {
      this.$router.push({ path: "/shopCar/address", query: { type: type } });
    },

    //获取地址列表
    getAddrList() {
      this.$http("get", "/sys/iaShoppingTrolley/getReceiptPage.do", {
        pageNum: 1,
        pageSize: 10000,
      }).then((res) => {
        if (res.code == "0000") {
          console.log("地址列表数据：", res);
          this.addressList = res.result.rows;
        }
      });
    },
    //编辑地址
    editAddr(item) {
      if(item.isDefault){
        item.isDefault = 1;
      }else{
        item.isDefault = 0;
      }
      this.$router.push({
        name: "shopCar-address",
        query: { type: "edit", item: JSON.stringify(item) },
      });
    },

    //删除一条地址
    delAddr(item, index) {
      var list = JSON.parse(JSON.stringify(this.addressList));

      this.$confirm("您确认要删除该地址吗。", "删除地址？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //确认：执行删除操作
          this.$http("delete", "/sys/iaShoppingTrolley/delReceiptDetail.do", {
            id: item.id, //地址id
          }).then((res) => {
            if (res.code == "0000") {
              list.splice(index, 1);
              this.addressList = list;
            }
          });
        })
        .catch(() => {
          //取消：不执行任何操作
        });
    },

    //获取选择的 商品数据
    getSlGodds(list) {
      console.log(list);
      var allIndex = [];
      var selectList = [];
      for (var k in list) {
        if (list[k].isSelect) {
          allIndex.push(Number(k));
          selectList.push(list[k]);
        }
      }
      console.log(allIndex);
      console.log("选择的购物车数据：", selectList);
      this.goodsList = selectList; //赋值挑选出的 用户选择的商品数据
    },

    //获取商品id
    getGoodSlDataId() {
      var list = JSON.parse(JSON.stringify(this.goodsList));
      var allIndex = [];
      var selectList = [];
      for (var k in list) {
        if (list[k].isSelect) {
          allIndex.push(Number(k));
          selectList.push(list[k]);
        }
      }
      console.log(allIndex);
      if (allIndex.length == 0) {
        this.$message.error("请选择商品");
        return;
      }
      console.log("选择的购物车数据：", selectList);

      var selectGoodIds = [];
      for (let index = 0; index < selectList.length; index++) {
        const element = selectList[index];
        selectGoodIds.push(element.id);
      }

      console.log("选择的购物车数据Id：", selectGoodIds);

      return selectGoodIds;
    },
    //设置默认地址
    setUpdateDefaultAddr(addrItem, defaultStr) {
      this.$http("put", "/sys/iaShoppingTrolley/updateDefault.do", {
        id: addrItem.id,
        isDefault: defaultStr, //默认地址(0:否;1:是)
      }).then((res) => {
        if (res.code == "0000") {
          this.$message({
            type: "success",
            message: "设置默认地址成功",
          });
        }
      });
    },
    //获取默认的用户地址
    getDefaultAddId() {
      var list = this.addressList;
      for (var k in list) {
        if (list[k].isDefault == true) {
          return list[k].id;
        }
      }
    },
    //提交下单
    submitClick() {
      var addrIdStr = this.getDefaultAddId();
      if (addrIdStr == null || addrIdStr === "") {
        this.$message.error("请设置默认收货地址");
        return;
      }

      var shoppingIds = this.getGoodSlDataId();
      var shoppingIdsStr = "";

      if (shoppingIds.length > 0) {
        shoppingIdsStr = shoppingIds.join(",");
      }

      let param = {
        id: addrIdStr, //收货人id
        shoppingIds: shoppingIdsStr, //购物车记录id
      };

      this.$http("post", "/sys/placeOrder/placeOrder.do", param).then((res) => {
        if (res.code == "0000") {
          this.$http("get", "/sys/iaShoppingTrolley/findPage.do", {
            pageNum: 1,
            pageSize: 10,
          }).then((res) => {
            if (res.code == "0000") {
              this.$message({
                type: "success",
                message: "下单成功,5s后将会返回首页",
              });
              this.$store.commit("joinCar", res.result.total);
              setTimeout(() => {
                this.$router.push("/");
              }, 5000);
            }
          });
        }
      });
    },
  },
};
</script>
<style scoped>
.box {
  width: 1200px;
  margin: 0 auto;
  min-height: 400px;
  background: #fff;
  padding-bottom: 30px;
}
.address-box {
  width: 1049px;
  min-height: 183px;
  border: 1px solid #e6e6e6;
  margin: 34px auto;
  padding: 0 30px 30px 30px;
  box-sizing: border-box;
}
.address-title {
  height: 66px;

  border-bottom: 1px solid #e1e1e1;
}
.address-title p:nth-child(1) {
  width: 100px;
  height: 22px;
  font-size: 16px;
  font-weight: 500;
  color: #262626;
  margin-left: 30px;
  margin-top: 19px;
}
.add-address-btn {
  width: 112px;
  height: 30px;
  background: #ffffff;
  border: 1px solid #ee781b;
  text-align: center;
  color: #ee781b;
  font-size: 14px;
  line-height: 30px;
  cursor: pointer;
  margin-top: 17px;
  margin-right: 30px;
}
.add-address-btn:active {
  background: #ee781b;
  color: #fff;
}
.edit p {
  float: left;
  width: 60px;
  color: #ee781b;
  font-size: 14px;
  cursor: pointer;
}
.edit p:hover {
  text-decoration: underline;
}
.address-list {
  margin-top: 20px;
}
.address-list .name {
  color: #262626;
  font-size: 16px;
  width: 80px;
}
.address-list .address {
  color: #262626;
  font-size: 16px;
  width: 340px;
}
.address-list .phone {
  color: #262626;
  font-size: 16px;
  width: 170px;
  margin-right: 80px;
}
.address-list .set-default img {
  width: 16px;
  height: 16px;
  cursor: pointer;
  margin-bottom: 4px;
}
.address-list .set-default span {
  color: #262626;
  font-size: 16px;
}
.goods-box {
  width: 1049px;
  margin: 10px auto;
}
.goods-table-head {
  height: 50px;
  background: #f6f6f6;
  border-radius: 4px;
  line-height: 50px;
}
.goods-table-head p {
  float: left;
  font-size: 14px;
  color: #262626;
}
.goods-table-head p:nth-child(1) {
  width: 527px;
  margin-left: 49px;
}
.goods-table-head p:nth-child(2) {
  margin-right: 100px;
}
.goods-table-head p:nth-child(3) {
  margin-right: 105px;
}
.goods-table-head p:nth-child(4) {
  margin-right: 104px;
}
.goods-box-list {
  margin-top: 10px;
}
.goods-list {
  height: 100px;
  background: #ffffff;
  border: 1px solid #e6e6e6;
  margin-bottom: 10px;
  padding: 14px 49px;
  box-sizing: border-box;
}
.goods-info {
  width: 420px;
  margin-top: 5px;
  margin-right: 60px;
}
.goods-info .goods-pic {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  margin-right: 20px;
}
.goods-info-detail p.goods-name {
  font-size: 14px;
  color: #383838;
  margin-top: 2px;
  margin-bottom: 4px;
}
.goods-info-detail p.other-info {
  color: #797979;
  font-size: 12px;
}
.goods-info-detail p.other-info span:nth-child(1) {
  margin-right: 39px;
}
.price {
  width: 120px;
  text-align: center;
  margin-top: 30px;
  color: #de3322;
  font-size: 16px;
}
.small-total {
  color: #de3322;

  width: 120px;
  text-align: center;
  margin-top: 23px;
  margin-left: 10px;
}
.small-total span {
  font-size: 16px;
}
.del-goods {
  font-size: 14px;
  color: #ee781b;
  width: 60px;
  text-align: right;
  line-height: 70px;
  cursor: pointer;
}
.del-goods:hover {
  text-decoration: underline;
}
.buy-num {
  margin-left: 10px;
}
.total-box {
  height: 59px;
  border: 1px solid #e6e6e6;
  margin-top: 29px;
}
.atonce-btn {
  width: 130px;
  height: 38px;
  background: #ee781b;
  border-radius: 2px;
  line-height: 38px;
  text-align: center;
  font-size: 14px;
  color: #fff;
  letter-spacing: 5px;
  margin-right: 49px;
  margin-top: 10px;
  margin-left: 70px;
  cursor: pointer;
}
.atonce-btn:hover {
  opacity: 0.7;
}
.total {
  margin-top: 15px;
}
.total span:nth-child(1) {
  color: #262626;
  font-size: 14px;
}
.total span:nth-child(2) {
  color: #de3322;
  font-size: 16px;
}
.wuliuClass {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
  -webkit-align-content: center;
  align-content: center;
  margin-left: 15px;
  margin-top: 14px;
  color: #262626;
  font-size: 16px;
}
</style>
<style>
.buy-num .el-input-number {
  width: 120px;
  margin-top: 16px;
}
</style>
